package com.rabbit.icore;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;
import java.util.UUID;

/**
 * 包装了RabbitTemplate类，为发送消息添加了一个CorrelationData
 */
public class RabbitTemplatePlus extends RabbitTemplate {
    @Autowired
    private Exchanges exchanges;

    /**
     * 普通发送数据
     *
     * @param body :消息体
     *             交换机固定了，可以配置文件中修改，路由键就是消息体中的appId
     */
    public void sendPlus(Map body,String routingKey) {
        CorrelationDataPlus correlationDataPlus = getCorrelationDataPlus(body,routingKey);
        this.convertAndSend(exchanges.getExchange(), correlationDataPlus.getRoutingKey(), body, correlationDataPlus);
    }


    /**
     * 用于confirm重发数据
     *
     * @param body
     *
     */
    public void sendPlus(Map body, CorrelationDataPlus correlationDataPlus) {
        this.convertAndSend(exchanges.getExchange(), correlationDataPlus.getRoutingKey(), body, correlationDataPlus);
    }

    public void sendPlus(Message message, String exchage, String routingKey) {
        CorrelationDataPlus correlationDataPlus = new CorrelationDataPlus();
        correlationDataPlus.setReturnedMessage(message);
        correlationDataPlus.setRoutingKey(routingKey);
        correlationDataPlus.setExchanges(Exchanges.exchanges);
        this.convertAndSend(exchage, routingKey, message, correlationDataPlus);
    }


    /**
     * 根据消息体创建 CorrelationDataPlus，用于confirm的重发
     *
     * @param body
     * @return
     */
    public CorrelationDataPlus getCorrelationDataPlus(Map body, String routingKey) {
        String msgId = UUID.randomUUID().toString();
        CorrelationDataPlus correlationDataPlus = new CorrelationDataPlus();
        correlationDataPlus.setId(msgId);
        correlationDataPlus.setExchanges(Exchanges.exchanges);
        correlationDataPlus.setRoutingKey(routingKey);
        correlationDataPlus.setBody(body);
        return correlationDataPlus;
    }

}
